import React, { useEffect, useState } from 'react';
import Modals from '../modals/Modals';
import './index.scss';
import { Cascader, message, ModalProps, Popover, Radio, RadioChangeEvent, Tag } from 'antd';
import { GetPoliciesRes } from '@/common/types';
import { DefaultOptionType } from 'antd/es/select';

interface Option {
  key?: string;
  value: string;
  label: React.ReactNode;
  name?: string;
  resource_type?: string;
  children?: Option[];
  isLeaf?: boolean;
  parentId?: null | string;
  type?: string;
}

interface DefaultValueProps {
  checked?: 'all' | 'part';
  id: string;
  name: string;
  type: string;
  resources?: GetPoliciesRes['resources'];
  defaultValue?: string[][];
  defaultName?: DefualtName;
}

interface DefualtNameValue {
  popover: string[];
  value: string;
}

interface DefualtName {
  dataset: DefualtNameValue[][];
  function: DefualtNameValue[][];
  database: DefualtNameValue[][];
}

interface Props extends ModalProps {
  open: boolean;
  onCancel: () => void;
  userData: DefaultValueProps[];
  options: Option[];
  onSubmit: (status: any[]) => void;
  isPreview?: boolean;
  isWorkflow?: boolean;
  isKnow?: boolean;
}

interface FindPathByValue {
  value: string[][];
  name: string[][];
}

const KnowPermissionsModal = ({
  onCancel,
  userData,
  options,
  onSubmit,
  isPreview,
  isWorkflow = false,
  isKnow = true,
  ...props
}: Props) => {
  const [user, setUser] = useState<DefaultValueProps[]>([]);

  const checkedStatus = (item: DefaultValueProps): 'all' | 'part' => {
    if (!item.resources) {
      return 'all';
    }

    if (item.resources.length === 0) {
      return 'all';
    }

    const all = item.resources.some(
      (item) => item.resource_type === '*' && item.resource_id === '*',
    );

    if (all) {
      return 'all';
    }

    const datasetStatus = item.resources.some(
      (item) => item.resource_type === 'dataset' && item.resource_id === '*',
    );
    const functionStatus = item.resources.some(
      (item) => item.resource_id === '*' && item.resource_type === 'function',
    );

    if (datasetStatus && functionStatus) {
      return 'all';
    }

    return 'part';
  };

  const handleSetDefaultValue = (value: DefaultValueProps): string[][] => {
    const filterAll = value.resources?.some(
      (item) => item.resource_id === '*' && item.resource_type === '*',
    );

    if (filterAll || value.resources?.length === 0) {
      return [];
    }

    let result: string[][] = [];

    const filterDataset = value.resources?.some(
      (item) => item.resource_id === '*' && item.resource_type === 'dataset',
    );

    const filterFunction = value.resources?.some(
      (item) => item.resource_id === '*' && item.resource_type === 'function',
    );

    const filterDatabase = value.resources?.some(
      (item) => item.resource_id === '*' && item.resource_type === 'database',
    );

    if (filterDataset) {
      result.push(['datasetRoot']);
    }

    if (filterFunction) {
      result.push(['functionRoot']);
    }

    if (filterDatabase) {
      result.push(['databaseRoot']);
    }

    const filterValue = value.resources?.filter(
      (item) =>
        !(
          (item.resource_id === 'dataset' && item.resource_type === '*') ||
          (item.resource_id === 'function' && item.resource_type === '*') ||
          (item.resource_id === 'database' && item.resource_type === '*')
        ),
    );

    if (filterValue && filterValue?.length > 0) {
      const filterValues = filterValue
        .map((item) => findPathByValue(item.resource_id).value)
        .filter((item) => item.length > 0);
      result = [...result, ...filterValues];
    }

    return result;
  };

  function findPathByValue(value: string): { value: string[]; name: string[] } {
    let path: string[] = [];
    let name: string[] = [];

    const findPath = (node: Option, value: string) => {
      if (node.value === value) {
        path.push(node.value);
        if (node.name) {
          name.push(node.name);
        }
        return true;
      }

      if (node.children) {
        for (let child of node.children) {
          if (findPath(child, value)) {
            path.push(node.value);
            if (node.name) {
              name.push(node.name);
            }
            return true;
          }
        }
      }

      return false;
    };

    for (let item of options) {
      if (findPath(item, value)) {
        break;
      }
    }

    return {
      value: path.reverse(),
      name: name.reverse(),
    };
  }

  const handleSetDefaultName = (value: DefaultValueProps) => {
    console.log('value', value);
    let result: DefualtName = {
      dataset: [],
      function: [],
      database: [],
    };

    const filterAll = value.resources?.some(
      (item) => item.resource_id === '*' && item.resource_type === '*',
    );

    if (filterAll) {
      result.dataset.push([{ popover: ['所有知识库'], value: '所有知识库' }]);
      result.function.push([{ popover: ['所有数据接口'], value: '所有数据接口' }]);
      result.database.push([{ popover: ['所有NL2SQL'], value: '所有NL2SQL' }]);
      return result;
    }

    if (value.resources?.length === 0) {
      return result;
    }

    const datasetSome = value.resources?.some(
      (item) => item.resource_id === '*' && item.resource_type === 'dataset',
    );

    const functionSome = value.resources?.some(
      (item) => item.resource_id === '*' && item.resource_type === 'function',
    );

    const databaseSome = value.resources?.some(
      (item) => item.resource_id === '*' && item.resource_type === 'database',
    );

    if (datasetSome) {
      result.dataset.push([{ popover: ['所有知识库'], value: '所有知识库' }]);
    }

    if (functionSome) {
      result.function.push([{ popover: ['所有数据接口'], value: '所有数据接口' }]);
    }

    if (databaseSome) {
      result.database.push([{ popover: ['所有NL2SQL'], value: '所有NL2SQL' }]);
    }

    const datasetValue = value.resources?.filter(
      (item) => item.resource_type && item.resource_type !== 'function',
    );
    const functionValue = value.resources?.filter(
      (item) => item.resource_type && item.resource_type === 'function',
    );
    const databaseValue = value.resources?.filter(
      (item) => item.resource_type && item.resource_type === 'database',
    );

    if (datasetValue && datasetValue?.length > 0) {
      datasetValue.map((item) => {
        const findPathName = findPathByValue(item.resource_id).name;
        if (findPathName.length !== 0) {
          result.dataset.push([
            { popover: findPathByValue(item.resource_id).name, value: item.resource_name },
          ]);
        }
      });
    }

    if (functionValue && functionValue.length > 0) {
      functionValue.map((item) => {
        const findPathName = findPathByValue(item.resource_id).name;
        if (findPathName.length !== 0) {
          result.function.push([
            { popover: findPathByValue(item.resource_id).name, value: item.resource_name },
          ]);
        }
      });
    }

    if (databaseValue && databaseValue.length > 0) {
      databaseValue.map((item) => {
        const findPathName = findPathByValue(item.resource_id).name;
        if (findPathName.length !== 0) {
          result.database.push([{ popover: findPathByValue(item.resource_id).name, value: item.resource_name },
          ]);
        }
      });
    }

    return result;
  };

  useEffect(() => {
    const data = userData.map((item) => {
      return {
        ...item,
        checked: checkedStatus(item),
        defaultValue: handleSetDefaultValue(item),
        defaultName: handleSetDefaultName(item),
      };
    });

    setUser(data);
  }, [userData]);

  const ModalsHeader = () => {
    return (
      <div className="text-sm">
        <div className="text-[#474C5F]">问答知识库权限设置</div>
        <div className="text-[#9FA4B7]">为不同的用户组选择不同的知识库，避免敏感知识库信息泄露</div>
      </div>
    );
  };

  const formatResources = (value: Option[][]) => {
    return value
      .map((innerArray) => {
        // 从每个内层数组中获取最后一项
        const lastArray = innerArray[innerArray.length - 1];
        return {
          resource_type: lastArray.type,
          resource_id: lastArray.value.includes('Root') ? '*' : lastArray.value,
          action: 'qa',
        };
      })
      .filter(Boolean);
  };

  const handleChange = (value: any, selectOptions: Option[][], index: number) => {
    setUser((prev) => {
      // 确保浅拷贝数组，避免直接修改原状态
      const updatedUser = [...prev];
      // 更新目标索引的用户数据
      updatedUser[index] = {
        ...updatedUser[index],
        resources: formatResources(selectOptions),
        defaultValue: value,
      };
      return updatedUser;
    });
  };

  const filter = (inputValue: string, path: DefaultOptionType[]) =>
    path.some(
      (option) => (option.label as string).toLowerCase().indexOf(inputValue.toLowerCase()) > -1,
    );

  const handleChangeRadio = (e: RadioChangeEvent, index: number) => {
    const value = e.target.value;

    setUser((prev) => {
      const updatedUser = [...prev];
      updatedUser[index] = {
        ...updatedUser[index],
        checked: value,
      };
      return updatedUser;
    });
  };

  const handleOk = () => {
    // const temp: DefaultValueProps[] = user.map((item) => {
    //   if (item.checked === 'all') {
    //     let resources = [
    //       {
    //         action: 'qa',
    //         resource_id: '*',
    //         resource_type: '*',
    //       },
    //     ];

    //     if (!isKnow) {
    //       resources = [{ action: 'qa', resource_id: '*', resource_type: 'dataset' }];
    //     }

    //     return {
    //       ...item,
    //       resources,
    //     };
    //   }
    //   return item;
    // });

    const temp = user;

    const filteredData = temp.filter((item) => item?.resources && item?.resources?.length > 0);

    if (filteredData.length !== temp.length) {
      message.error('请选择知识库或数据接口!');
      return;
    }

    const result = temp.map((item) => {
      return {
        target: {
          target_id: item.id,
          target_type: item.type,
        },
        resources: item.resources,
      };
    });

    // console.log('temp', temp);

    // console.log('result', result);

    onSubmit(result);
  };

  return (
    <Modals
      {...props}
      width={1060}
      title={<ModalsHeader />}
      zIndex={1001}
      onOk={handleOk}
      onCancel={onCancel}
    >
      <div className="max-h-[550px] overflow-y-auto">
        <table className="table-content w-full">
          <thead>
            <tr>
              <th className="table-content-left w-[306px]">用户组</th>
              <th className="table-content-right">权限</th>
            </tr>
          </thead>
          <tbody>
            {user.map((item, index) => (
              <tr key={index}>
                <th className={index !== userData.length - 1 ? `table-content-left` : ''}>
                  {item.name}
                </th>
                {isPreview ? (
                  <th
                    className="table-content-right"
                    style={{
                      borderBottom: index === userData.length - 1 ? 'none' : '1px solid #c9cdde',
                    }}
                  >
                    <div className="flex flex-wrap gap-[10px]">
                      {item.defaultName?.dataset.map((items) =>
                        items.map((data, dataIndex) => (
                          <Popover content={data.popover && data.popover.join('/')} key={dataIndex}>
                            <Tag color="blue">{data.value}</Tag>
                          </Popover>
                        )),
                      )}
                    </div>
                    <div className="mt-2 flex flex-wrap gap-[10px]">
                      {item.defaultName?.function.map((items) =>
                        items.map((data, dataIndex) => (
                          <Popover content={data.popover && data.popover.join('/')} key={dataIndex}>
                            <Tag color="purple">{data.value}</Tag>
                          </Popover>
                        )),
                      )}
                    </div>
                  </th>
                ) : (
                  <th
                    className="table-content-right"
                    style={{
                      borderBottom: index === userData.length - 1 ? 'none' : '1px solid #c9cdde',
                    }}
                  >
                    {/* <Radio.Group
                      // defaultValue={item.checked}
                      value={item.checked}
                      onChange={(e) => handleChangeRadio(e, index)}
                      className="flex w-full"
                    >
                      <Radio value={'all'}>所有知识库{isKnow ? '/数据接口' : ''}可问答</Radio>
                      {!isWorkflow && (
                        <div className="ml-[100px] inline-flex flex-1 flex-col">
                          <Radio value={'part'}>部分知识库{isKnow ? '/数据接口' : ''}可问答</Radio>
                          {item.checked === 'part' && (
                            <Cascader
                              placeholder="请选择知识库"
                              options={options}
                              onChange={(value, selectOptions) =>
                                handleChange(value, selectOptions, index)
                              }
                              changeOnSelect
                              className="!ml-4 !mt-1 !w-full"
                              key={'key'}
                              multiple
                              maxTagCount="responsive"
                              showSearch={{ filter }}
                              value={item.defaultValue}
                              // defaultValue={item.defaultValue}
                            />
                          )}
                        </div>
                      )}
                    </Radio.Group> */}

                    <Cascader
                      placeholder="请选择知识库"
                      options={options}
                      onChange={(value, selectOptions) => handleChange(value, selectOptions, index)}
                      changeOnSelect
                      className="!ml-4 !mt-1 !w-full"
                      key={'key'}
                      multiple
                      maxTagCount="responsive"
                      showSearch={{ filter }}
                      value={item.defaultValue}
                      // defaultValue={item.defaultValue}
                    />
                  </th>
                )}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </Modals>
  );
};

export default KnowPermissionsModal;
